﻿using System;

namespace DotNetCommon.Validate.Annotations;

/// <summary>
/// 字符串必须是正确的 email 格式, 示例:
/// <code>
/// [VMustEmail]
/// public string Email { get; set; }
/// </code>
/// </summary>
/// <remarks>
/// 注意: 
/// <list type="bullet">
/// <item>当属性不是字符串时, 会先调用 ToString() 转为字符串再进行判断, 这可以用于对非字符串类型的校验</item>
/// <item>默认字符串不能为 null, 如果允许字符串为 null, 使用 [VMustEmailIfNotNull] </item>
/// </list>
/// </remarks>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public sealed class VMustEmailAttribute(string errorMessage = null) : Attribute, IValidateAction
{
    public string ErrorMessage { get; set; } = errorMessage;

    public void Action(IValidateContext ctx)
    {
        ValidateStringExtensions.MustEmailAddressInternal(ctx, ctx.ModelValue?.ToString(), ErrorMessage);
    }
}

/// <summary>
/// 如果不为null, 则字符串必须是正确的 email 格式, 示例:
/// <code>
/// [VMustEmailIfNotNull]
/// public string Email { get; set; }
/// </code>
/// </summary>
/// <remarks>
/// 注意: 
/// <list type="bullet">
/// <item>当属性不是字符串时, 会先调用 ToString() 转为字符串再进行判断, 这可以用于对非字符串类型的校验</item>
/// </list>
/// </remarks>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public sealed class VMustEmailIfNotNullAttribute(string errorMessage = null) : Attribute, IValidateAction
{
    public string ErrorMessage { get; set; } = errorMessage;

    public void Action(IValidateContext ctx)
    {
        if (ctx.ModelValue == null) return;
        ValidateStringExtensions.MustEmailAddressInternal(ctx, ctx.ModelValue?.ToString(), ErrorMessage);
    }
}
